package com.sita.bike.ui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

import com.sita.bike.R;
import com.sita.bike.utils.FormatUtils;

import java.util.Date;

/**
 * 环形的进度条
 */
public class CircularProgressBar extends View {

    private Paint mPaint = new Paint();
    private RectF mRectF = new RectF();
    private int DEFAULT_COLOR = Color.WHITE;
    private int mBackgroundColor = DEFAULT_COLOR;
    private int mProgressColor = DEFAULT_COLOR;
    private float mStrokeWidth = 50f;//设置圆环的宽度
    private float mRadius = 0f;
    private long mTime = 0;
    private double mValue = 0;
    private String mCommonValue = "";
    private Drawable mIconResource;//绿色圆形背景图
    private Bitmap mIconBitmap;
    private int mFormat = 0;
    public Context context;

    private int mMaxValue = 100;
    private int mCurrentValue = 0;
    private float mBarThicknessFraction = 0;
    private long mAvgSpeed;

//    /**
//     * 进度条改变监听
//     * <p/>
//     * {@link #onChange(int duration, int progress, float rate)}
//     */
//    public interface OnProgressChangeListener {
//        /**
//         * 进度改变事件，当进度条进度改变，就会调用该方法
//         *
//         * @param duration 总进度
//         * @param progress 当前进度
//         * @param rate     当前进度与总进度的商 即：rate = (float)progress / duration
//         */
//        public void onChange(int duration, int progress, float rate);
//    }
//
//    private OnProgressChangeListener mOnChangeListener;
//
//    /**
//     * 设置进度条改变监听
//     *
//     * @param l
//     */
//    public void setOnProgressChangeListener(OnProgressChangeListener l) {
//        mOnChangeListener = l;
//    }

    public CircularProgressBar(Context context) {
        super(context);
        this.context = context;
    }

    public CircularProgressBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initProgressBar(context, attrs);
    }


    private void initProgressBar(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CircularProgressBar);

        mBackgroundColor = typedArray.getColor(R.styleable.CircularProgressBar_backColor, DEFAULT_COLOR);
        mProgressColor = typedArray.getColor(R.styleable.CircularProgressBar_progressColor, DEFAULT_COLOR);
        mBarThicknessFraction = typedArray.getFloat(R.styleable.CircularProgressBar_barThickness, 0.2f);
        mFormat = typedArray.getInt(R.styleable.CircularProgressBar_format, 0);
        if (typedArray.hasValue(R.styleable.CircularProgressBar_barIcon)) {
            mIconResource = typedArray.getDrawable(R.styleable.CircularProgressBar_barIcon);
        }

    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {

        int halfWidth = getWidth() / 2;
        int halfHeight = getHeight() / 2;
        float radius = halfWidth < halfHeight ? halfWidth : halfHeight;
        mStrokeWidth = radius * mBarThicknessFraction;
        float halfStrokeWidth = mStrokeWidth / 2;

        int x0 = halfWidth;
        int y0 = halfHeight;


        // 设置画笔
        mPaint.setColor(mBackgroundColor);
        mPaint.setDither(true);
        mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(mStrokeWidth);
        mPaint.setStyle(Paint.Style.STROKE);    //设置图形为空心

        // 画背景
        canvas.drawCircle(halfWidth, halfHeight, radius - halfStrokeWidth, mPaint);

        // 画当前进度的圆环
        mPaint.setColor(mProgressColor);    // 改变画笔颜色
        float angle = getRateOfProgress() * 360;
        mRectF.top = halfHeight - radius + halfStrokeWidth;
        mRectF.bottom = halfHeight + radius - halfStrokeWidth;
        mRectF.left = halfWidth - radius + halfStrokeWidth;
        mRectF.right = halfWidth + radius - halfStrokeWidth;
        canvas.drawArc(mRectF, 90, angle, false, mPaint);

//        int xOffset = (int) ((radius - halfStrokeWidth) * Math.cos(Math.toRadians(angle + 150)));
//        int yOffset = (int) ((radius - halfStrokeWidth) * Math.sin(Math.toRadians(angle + 150)));

//
        // 数字
        if (mFormat == 0) {
            Paint mSpeedTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mSpeedTextPaint.setTextSize(radius * 0.8f);
            mSpeedTextPaint.setTextAlign(Paint.Align.CENTER);
            mSpeedTextPaint.setColor(Color.BLACK);
            mSpeedTextPaint.setTypeface(Typeface.DEFAULT_BOLD);

            canvas.save();
            float textWidthScale = 0.8f;
            canvas.scale(textWidthScale, 1f);
            // speed number
            //总里程数小于等于10，保留一位小数，大于10公里数取整。
            String drawableValue = null;
            if (mValue > 10) {
                drawableValue = String.valueOf((int) mValue);
            } else {
                drawableValue = String.valueOf(mValue);
            }
            canvas.drawText(drawableValue, x0 / textWidthScale, y0 + radius * 0.2f, mSpeedTextPaint);
            canvas.restore();

        }
        // 时间
        else if (mFormat == 1) {
            Paint mSpeedTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mSpeedTextPaint.setTextSize(radius * 0.5f);
            mSpeedTextPaint.setTextAlign(Paint.Align.CENTER);
            mSpeedTextPaint.setColor(Color.BLACK);
            mSpeedTextPaint.setTypeface(Typeface.DEFAULT_BOLD);

            canvas.save();
            float textWidthScale = 0.8f;
            canvas.scale(textWidthScale, 1f);
            // speed number
            long seconds = mTime / 1000;
            //如果seconds 大于等于60秒则时间的格式显示为小时分钟，否则显示为分钟和秒。
            if (seconds >= 60) {
                canvas.drawText(FormatUtils.formatShortTimeHHMM(mTime), x0 / textWidthScale, y0 + radius * 0.2f, mSpeedTextPaint);
            } else {
                canvas.drawText(FormatUtils.formatShortTimeMMSS(mTime), x0 / textWidthScale, y0 + radius * 0.2f, mSpeedTextPaint);
            }

            canvas.restore();
        }
        // 图标
        else if (mFormat == 2) {
            RectF rectf = new RectF();
            float h = radius * (1f - mBarThicknessFraction) * 0.8f;
            rectf.left = x0 - h;
            rectf.top = y0 - h;
            rectf.right = x0 + h;
            rectf.bottom = y0 + h;
            //mIconBitmap = BitmapFactory.decodeResource(GlobalContext.getGlobalContext().getResources(), mIconResource);
            mIconResource.setBounds((int) rectf.left, (int) rectf.top, (int) rectf.right, (int) rectf.bottom);
            mIconResource.draw(canvas);
//            canvas.drawBitmap(mIconBitmap, null, rectf, mPaint);
        }
        canvas.save();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                invalidate();
            }
        }
    };

    /**
     * 得到当前的进度的比率
     * <p> 用进度条当前的值 与 进度条的最大值求商 </p>
     *
     * @return
     */
    private float getRateOfProgress() {
        return (float) mCurrentValue / mMaxValue;
    }

    public void setIconResource(Drawable iconResource){
        this.mIconResource = iconResource;
    }

    public void setMaxValue(int maxValue) {
        this.mMaxValue = maxValue;
    }

    public void setProgress(int curValue) {
        mCurrentValue = curValue;
        this.invalidate();
    }

    public void setProgress(int curValue, int maxValue) {
        this.mCurrentValue = curValue;
        this.mMaxValue = maxValue;
        this.invalidate();
    }

    public void setCommonValue(String commonValue) {
        mCommonValue = commonValue;
        this.invalidate();
    }

    public void setTime(long time) {
        mTime = time;
        this.invalidate();
    }


    public void setValue(double value) {
        mValue = value;
        this.invalidate();
    }

}
